/**
 * Created by fyf on 2016/9/14.
 */
const request = require('request');
const REQUEST_URL = require('./weChatInterface');
const PARAMS_ARR = {
    "appid": config.weChat.AppID,
    "secret": config.weChat.AppSecret
};
exports.requestToWeChat = function (params) {
    return new Promise(function (resolve, reject) {
        let options = getRequestOptions(params);
        printLog(JSON.stringify(options));
        request(options, function (err, response, body) {
            printLog("=requestToWeChat=",body);
            if (err) {
                reject(err);
            } else {
                let _body = JSON.parse(body);
                if(_body.errcode){
                    reject({code:100,errorInfo:_body.errmsg});
                }else{
                    resolve(_body);
                }
            }
        })
    });
};

function getRequestOptions(params) {
    return {
        uri: getRequestUrl(params.serviceCode, params.queryParams),
        headers: {"Content-Type": "application/json",},
        method: REQUEST_URL[params.serviceCode].method,
        body: JSON.stringify(params.data || {})
    }
}
function getRequestUrl(serviceCode, params) {
    let urlObj = REQUEST_URL[serviceCode];
    let url = urlObj.url;
    let queryUrl = "";
    for (let i in urlObj.staticParams)
        queryUrl += "&" + urlObj.staticParams[i] + "=" + PARAMS_ARR[urlObj.staticParams[i]];
    for (let i in urlObj.otherParams)
        queryUrl += "&" + urlObj.otherParams[i] + "=" + params[urlObj.otherParams[i]];
    for (let i in urlObj.fixedParams)
        queryUrl += "&" + i + "=" + urlObj.fixedParams[i];
    if (queryUrl)
        url += "?" + queryUrl.substring(1);
    return url;
}




